﻿using System.Collections.Generic;
using System.IO;

using CY_MVC.ViewTemplate;
using NVelocity;
using NVelocity.Context;

namespace ViewNVelocity
{
    class ViewTemplate : BaseViewTemplate
    {
        public ViewTemplate()
        {
            Extension = ".vm";
        }

        private Template m_Template;

        private Template Template
        {
            get
            {
                return m_Template;
            }
            set
            {
                m_Template = value;
            }
        }

        private IContext m_Context;
        private TextWriter m_Writer;

        public override void SetTemplateFile(string p_TemplateFile)
        {
            base.SetTemplateFile(p_TemplateFile);
            Template = TemplateContext.GetVelocity().GetTemplate(TemplateFile);
        }

        public override string BuildString(IDictionary<string, object> p_ViewData)
        {
            if (Template == null)
            {
                Template = TemplateContext.GetVelocity().GetTemplate(TemplateFile);
            }

            m_Context = new VelocityContext();

            foreach (var item in p_ViewData)
            {
                m_Context.Put(item.Key, item.Value);
            }
            m_Writer = new StringWriter();

            Template.Merge(m_Context, m_Writer);

            return m_Writer.ToString();
        }
    }
}
